import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef, useContext } from 'react';
import { getAllArea, IArea, saveArea, updateArea, deleteAreaApi } from 'api/Area';
import { useRequest, useHover } from 'ahooks';
import {
    FormOutlined,
    EnvironmentOutlined,
    CheckOutlined,
    CloseOutlined,
    PlusSquareOutlined,
    ExclamationCircleOutlined,
} from '@ant-design/icons';
import './index.less';
import { Input, message, Spin, Tag, Modal, Badge } from 'antd';
import { ProviderContext } from 'store';
interface AreaItemProps {
    area: IArea;
    areas: IArea[];
    setAreas: (value: IArea[]) => void;
    inEditArea: string;
    setInEditArea: (value: string) => void;
    updateAreas: Function;
    selectedArea: number;
    setSelectedArea: (value: any) => void;
    editable?: boolean;
}
const AreaItem = (props: AreaItemProps) => {
    const hoverRef: any = useRef();
    const isHover = useHover(hoverRef);
    const [newAreaName, setNewAreaName] = useState('');
    const [alarmCount, setAlarmCount] = useState(0)
    /** reducer初始化 */
    const { state, asyncActions } = useContext(ProviderContext);
    useEffect(() => {
        console.log(state)
        const currentAlarms = state?.alarms.filter((item: any) => item.areaId === props.area.id) || []
        setAlarmCount(currentAlarms.length)
    }, [state])
    /** 编辑区域 */
    const editArea = () => {
        props.setAreas(props.areas.filter((item) => item.id !== undefined));
        props.setInEditArea(props.area.name);
        setNewAreaName(props.area.name);
    };
    /** 保存编辑或保存新增 */
    const createOrUpdateArea = (e: any) => {
        e.stopPropagation();
        if (!newAreaName) {
            message.warning('区域名不能为空');
            return;
        }
        const { id, name } = props.area;
        if (id) {
            if (newAreaName === name) return;
            updateArea({ id, name: newAreaName }).then(() => {
                message.success('更新区域名成功');
                props.setInEditArea('');
                props.updateAreas();
            });
        } else {
            saveArea({ name: newAreaName }).then(() => {
                message.success('新增区域成功');
                props.updateAreas();
            });
        }
    };
    /** 取消编辑或新增 */
    const cancelEdit = (e: any) => {
        e.stopPropagation();
        props.setAreas(props.areas.filter((item) => item.id !== undefined));
        props.setInEditArea('');
    };
    /** 删除区域 */
    const deleteArea = (e: any) => {
        e.stopPropagation();
        Modal.confirm({
            title: '删除',
            icon: <ExclamationCircleOutlined />,
            content: '是否确认删除当前区域?',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                if (props.area.id) {
                    deleteAreaApi([props.area.id]).then(() => {
                        message.success('删除成功');
                        props.updateAreas().then((result: any) => {
                            props.setSelectedArea(result[0].id || 0);
                        });
                    });
                }
            },
        });
    };
    return (
        <div
            className={`area-item flex-align ${props.selectedArea === props.area.id && 'selected-area'}`}
            ref={hoverRef}
            onClick={() => props.setSelectedArea(props.area.id)}
        >
            <EnvironmentOutlined className="mr10" />
            {props.inEditArea === props.area.name ? (
                <>
                    <Input
                        className="area-name"
                        defaultValue={newAreaName}
                        onClick={(e) => e.stopPropagation()}
                        onChange={(e) => setNewAreaName(e.target.value.trim())}
                        size="small"
                    />
                    <CheckOutlined className="ml10 pointer" onClick={createOrUpdateArea} />
                    <CloseOutlined className="ml10 pointer" onClick={cancelEdit} />
                </>
            ) : (
                <Badge count={alarmCount}>
                    <Tag className="area-name text-center" color={props.selectedArea === props.area.id ? '#1890ff' : ''}>
                        {props.area.name}{' '}
                    </Tag>
                    {props.editable && isHover && <FormOutlined className="ml10" onClick={editArea} />}
                    {props.area.id && props.editable && isHover && <CloseOutlined className="ml10" style={{ color: 'red' }} onClick={deleteArea} />}
                </Badge>
            )}
        </div>
    );
};

interface AreaProps {
    selectedArea: number;
    setSelectedArea: (value: number) => void;
    editable?: boolean;
    canSelectAll?: boolean;
}
/** 区域展示 */
const Area = ({ selectedArea, setSelectedArea, editable = false, canSelectAll = true }: AreaProps, ref: any) => {
    const [areas, setAreas] = useState<IArea[]>([]);
    /** 获取全部区域 */
    let { run, loading } = useRequest(getAllArea, {
        manual: true,
        onSuccess: (result) => {
            setAreas(result);
            if (!canSelectAll) {
                setSelectedArea(result[0].id || 0);
            }
        },
    });
    useEffect(() => {
        run();
    }, []);
    /** 暴露接口 */
    useImperativeHandle(ref, () => {
        let areaNameMap: any = {};
        areas.map((area) => {
            area.id && (areaNameMap[area.id] = area.name);
        });
        return {
            areas,
            areaNameMap,
        };
    });
    const [inEditArea, setInEditArea] = useState('');
    /** 新建区域 */
    const createArea = () => {
        if (areas.find((item) => item.id === undefined)) return;
        setAreas([...areas, { name: '' }]);
        setInEditArea('');
    };
    const selectAll = () => {
        if (canSelectAll) {
            setSelectedArea(-1);
        }
    };
    const areaProps = {
        areas,
        setAreas,
        inEditArea,
        setInEditArea,
        updateAreas: run,
        selectedArea,
        setSelectedArea,
        editable,
    };
    return (
        <Spin spinning={loading}>
            <div className="area-view">
                <div className={`pointer ${selectedArea === -1 && 'selected-area'}`} onClick={selectAll}>
                    区域总览
                </div>
                <div className="area-list">
                    {areas ? (
                        areas.map((item: IArea) => <AreaItem key={item.name} area={item} {...areaProps}></AreaItem>)
                    ) : (
                        <div>暂无区域</div>
                    )}
                </div>
                {editable && <PlusSquareOutlined className="pointer ml10" onClick={createArea} />}
            </div>
        </Spin>
    );
};
export default forwardRef(Area);
